<template>
  <div>
    <el-space direction="vertical" fill wrap :fill-ratio="fillRatio" style="width: 100%">
      <!-- 商品(Spu)介绍 -->
      <el-card>
        <span>商品(Spu)介绍</span>
        <!-- 表单 -->
        <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="rules"
          label-width="120px"
          class="demo-ruleForm"
        >
          <el-form-item label="商品名称" prop="title">
            <el-input v-model="ruleForm.title" />
          </el-form-item>

          <el-form-item label="原始价格" prop="originalPrice">
            <el-input v-model="ruleForm.originalPrice" placeholder="0">
              <template #append>元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="当前价格" prop="price">
            <el-input v-model="ruleForm.price" placeholder="0">
              <template #append>元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="VIP价格" prop="vipPrice">
            <el-input v-model="ruleForm.vipPrice" placeholder="0">
              <template #append>元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="剩余库存" prop="stock">
            <el-input v-model="ruleForm.stock" disabled placeholder="0" />
          </el-form-item>
          <el-form-item label="运费模板" prop="freightTemplateId">
            <!-- 选择器 -->
            <el-select v-model="ruleForm.freightTemplateId" placeholder="请输入运费模板">
              <el-option
                v-for="item in FreightOptions"
                :key="item.id"
                :label="item.title"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="是否在售" prop="status">
            <el-radio-group v-model="ruleForm.status">
              <el-radio :label="1">在售</el-radio>
              <el-radio :label="0">下架</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="商品图片">
            <el-upload
              action="http://192.168.1.188:8080/upload/admin"
              list-type="picture-card"
              :headers="headers"
              :on-success="handleAvatarSuccess"
            >
              <template #default>
                <img style="width:100%;height:100%" :src="ruleForm.img" class="avatar" />
              </template>
            </el-upload>
          </el-form-item>
          <el-form-item label="商品单位" prop="unit">
            <el-input v-model="ruleForm.unit" placeholder="请输入商品单位"></el-input>
          </el-form-item>
          <el-form-item label="所属类目">
            <!-- 所属类目 -->
            <el-cascader
              v-model="ruleForm.categoryId"
              :options="productOptions"
              placeholder="请选择类目"
              :props="props"
              clearable
            />
          </el-form-item>
          <el-form-item label="商品简介">
            <el-input v-model="ruleForm.description" />
          </el-form-item>
          <el-form-item label="商品详细介绍" prop="detail">
            <!-- 富文本编译器组件 -->
            <!-- 渲染到template组件 -->
            <editor @update:modelValue="ruleForm.detail=$event" v-model="ruleForm.detail"></editor>
          </el-form-item>
        </el-form>
      </el-card>
      <!-- 商品参数 -->
      <el-card>
        <span>商品参数</span>
        <p>
          <el-button class="button" type="primary" plain @click="paraAdd">添加</el-button>
        </p>
        <!-- 点击添加按钮显示商品参数==弹框== -->
        <el-dialog v-model="diFoViPara" title="设置商品参数">
          <el-form :rules="rules" status-icon :model="formPara">
            <!-- status-icon === 是否在输入框中显示校验结果反馈图标 -->
            <el-form-item label="商品参数名称" prop="attribute">
              <el-input v-model="formPara.attribute" autocomplete="off" />
            </el-form-item>
            <el-form-item label="商品参数值" prop="value">
              <el-input v-model="formPara.value" autocomplete="off" />
            </el-form-item>
          </el-form>

          <template #footer>
            <span class="dialog-footer">
              <el-button @click="diFoViPara=false">取消</el-button>
              <el-button type="primary" @click="confirmPara">确定</el-button>
            </span>
          </template>
        </el-dialog>
        <!-- 商品参数====表格 -->
        <el-table :data="ruleForm.attributeList" stripe style="width: 100%">
          <el-table-column prop="attribute" label="商品参数名称" align="center" />
          <el-table-column prop="value" label="商品参数值" align="center" />
          <el-table-column prop label="操作" align="center">
            <template #default="scope">
              <el-button size="small" type="danger" @click="handleParaDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <!-- 规格维度 -->
      <el-card>
        <span>规格维度</span>
        <p>
          <el-button class="button" type="primary" plain @click="spaceAdd">添加</el-button>
        </p>
        <!-- 点击添加按钮显示商品参数==弹框== -->
        <el-dialog v-model="diFoViSpace" title="创建规格">
          <el-form :rules="rules" status-icon :model="formSpace">
            <!-- status-icon === 是否在输入框中显示校验结果反馈图标 -->
            <el-form-item label="类型名称" prop="title">
              <el-input v-model="formSpace.title" placeholder="请输入类型名称" />
            </el-form-item>
          </el-form>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="diFoViSpace=false">取消</el-button>
              <el-button type="primary" @click="confirmSpace">确定</el-button>
            </span>
          </template>
        </el-dialog>
        <!-- 规格维度====表格 -->
        <el-table :data="ruleForm.specificationList" stripe style="width: 100%">
          <el-table-column prop label="维度ID" align="center" />
          <el-table-column prop="title" label="维度名称" align="center" />
          <el-table-column
            prop="gmtCreate"
            label="创建时间"
            align="center"
          >{{ new Date().formate(new Date())}}</el-table-column>
          <el-table-column prop label="操作" align="center">
            <template #default="scope">
              <el-button size="small" type="primary" @click="handleEdit(scope.row)">修改</el-button>
              <el-button size="small" type="danger" @click="handleDelete(scope.row,scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <!-- 商品(Sku)详情 -->
      <el-card>
        <span>商品(Sku)详情</span>
        <p>
          <el-button class="button" type="primary" plain @click="diFoViBatch=true">批量定价</el-button>
        </p>
        <!-- 标签 -->

        <el-space
          style="display: block;"
          direction="vertical"
          v-for="(tag,index) in ruleForm.specificationList"
          :key="index"
        >
          <div>
            <!-- 这个和不加就会出现下面的标签框是百分比的状况 -->
            <!-- 前面的类型 -->
            <el-tag type="warning">{{ tag.title }}</el-tag>
            <!-- 后面的添加 -->
            <el-tag
              v-for="(tagSun,ind) in tag.values"
              :key="ind"
              closable
              :disable-transitions="false"
              @close="handleClose(tag)"
            >{{ tagSun }}</el-tag>
            <el-input
              style="width:100px"
              v-if="tag.inputSkuTagVisible"
              :ref="'input'+index"
              v-model="tag.inputSkuTagValue"
              size="small"
              @keyup.enter="handleInputConfirm(tag.inputSkuTagValue,index)"
              @blur="handleInputConfirm(tag.inputSkuTagValue,index)"
            />
            <el-button v-else size="small" @click="showInput(index)">添加</el-button>
          </div>
        </el-space>

        <!-- 点击添加按钮显示批量定价==弹框== -->
        <el-dialog v-model="diFoViBatch" title="创建规格">
          <el-form :rules="rules" status-icon :model="formBatch">
            <!-- status-icon === 是否在输入框中显示校验结果反馈图标 -->
            <el-form-item label="现价(￥)">
              <el-input-number v-model="formBatch.price" :min="1" :precision="2" />
            </el-form-item>
            <el-form-item label="VIP价(￥)">
              <el-input-number v-model="formBatch.vipPrice" :min="1" :precision="2" />
            </el-form-item>
            <el-form-item label="吊牌价(￥)">
              <el-input-number v-model="formBatch.originalPrice" :min="1" :precision="2" />
            </el-form-item>
          </el-form>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="diFoViBatch=false">取消</el-button>
              <el-button type="primary" @click="confirmBatch">确定</el-button>
            </span>
          </template>
        </el-dialog>
        <!-- 商品(Sku)详情====表格 -->
        <el-table :data="ruleForm.skuList" border stripe style="width: 100%">
          <!-- 添加的内容---（又会添加一列内容） -->
          <el-table-column
            :prop="'id_'+tag.title"
            :label="tag.title"
            align="center"
            v-for="(tag,index) in ruleForm.specificationList"
            :key="index"
          ></el-table-column>
          <el-table-column prop="gmtStart" label="SkuId" align="center"></el-table-column>
          <el-table-column prop="price" label="￥价格(元)" align="center">
            <template #default="scope">
              <el-input-number v-model="scope.row.price" :min="1" :precision="2" />
            </template>
          </el-table-column>
          <el-table-column prop="vipPrice" label="￥VIP价(元)" align="center">
            <template #default="scope">
              <el-input-number v-model="scope.row.vipPrice" :min="1" :precision="2" />
            </template>
          </el-table-column>
          <el-table-column prop="originalPrice" label="￥掉牌价(元)" align="center">
            <template #default="scope">
              <el-input-number v-model="scope.row.originalPrice" :min="1" :precision="2" />
            </template>
          </el-table-column>
          <el-table-column prop="stock" label="库存(件)" align="center">
            <template #default="scope">
              <el-input-number v-model="scope.row.stock" :min="1" :precision="2" />
            </template>
          </el-table-column>
          <el-table-column prop="weight" label="重量(克)" align="center">
            <template #default="scope">
              <el-input-number v-model="scope.row.weight" :min="1" :precision="2" />
            </template>
          </el-table-column>
          <el-table-column prop="img" label="SKU图片" align="center">
            <template #default>
              <el-upload
                action="http://192.168.1.188:8080/upload/admin"
                list-type="picture-card"
                :headers="headers"
              ></el-upload>
            </template>
          </el-table-column>
          <el-table-column prop="barCode" label="条形码" align="center">
            <template #default="scope">
              <el-input v-model="scope.row.barCode" placeholder="0">
                <template #append>
                  <el-button @click="scope.row.barCode=+new Date()">随机数</el-button>
                </template>
              </el-input>
            </template>
          </el-table-column>
          <el-table-column prop label="操作" align="center">
            <template #default="scope">
              <el-button size="small" type="primary" @click="handleEdit(scope.row)">修改</el-button>
              <el-button size="small" type="danger" @click="handleDelete(scope.row,scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <div style="flex: auto">
        <el-button>取消</el-button>
        <el-button type="primary" @click="saveGoods('ruleFormRef')">保存商品</el-button>
      </div>
    </el-space>
  </div>
</template>

<script>
import http from "@/util/http";
import Cookies from "js-cookie";
// 富文本编译器
import Editor from "../../../components/MyTinymce.vue";
import { mapGetters } from "vuex";
export default {
  // 注册tinymce组件

  components: {
    editor: Editor,
    mapGetters,
  },
  props: {
    value: {
      type: String,
      default: "",
    },
    disabled: {
      type: Boolean,
      default: false,
    },
  },
  computed: {
    ...mapGetters(["productEditData"]),
  },
  data() {
    return {
      // 富文本编辑器的所需要传的值
      newValue: "",
      tinymce: "",

      //  创建的商品图片请求头
      headers: { AdminToken: Cookies.get("token") },
      // 间距的填充父容器的比例值
      fillRatio: 100,
      init: {
        selector: "#tinydemo", //容器，可使用css选择器
        language: "zh_CN", //调用放在langs文件夹内的语言包
        toolbar: false, //隐藏工具栏
        menubar: false, //隐藏菜单栏
        inline: true, //开启内联模式
        plugins: ["quickbars", "link", "table"], //选择需加载的插件
        //选中时出现的快捷工具，与插件有依赖关系
        quickbars_selection_toolbar:
          "bold italic forecolor | link blockquote quickimage",
      },
      // 表单的数据
      ruleForm: {
        imgList: [],
        title: "", //商品名称
        stock: 0, //剩余库存
        freightTemplateId: "", //运费模板
        status: 1, //是否在售
        img: "", //商品图片
        unit: "", //商品单位
        categoryId: "", //所属类目
        description: "", //商品简介
        detail: "", //商品详细介绍
        // 商品(sku)详情
        price: 0, //价格
        originalPrice: 0, //吊牌价
        vipPrice: 0, //VIP价格
        attributeList: [], //商品参数表格数据
        //规格维度
        specificationList: [],
        skuList: [], //商品详情
      },
      // 设置商品参数的弹框---表单的数据
      formPara: {
        attribute: "",
        value: "",
      },
      // 规格维度---表单的数据
      formSpace: {
        id: 1,
        title: "",
      },

      //  商品(Sku)详情--表单的数据--批量定价
      formBatch: {
        price: "",
        vipPrice: "",
        originalPrice: "",
      },
      // 	运费模板--请求的数据
      FreightOptions: [],
      // 	搜索分类---商品树
      productOptions: [],
      // 搜索分类---商品获取SPU树配置选项
      props: {
        checkStrictly: true,
        label: "title",
        value: "id",
        children: "childrenList",
        emitPath: false, //如果emitPath为false的
      },
      // 设置商品参数的弹框的布尔值
      diFoViPara: false,
      // 创建规格的弹框的布尔值
      diFoViSpace: false,
      // 批量定价的弹框的布尔值
      diFoViBatch: false,
      // 商品详情标签的11布尔值
      inputVisible: false,
      // 商品详情标签的input值
      inputValue: "",
      // 规则
      rules: {
        //商品名称不能为空
        title: [
          {
            trigger: "blur",
            required: true,
            message: "商品名称不能为空",
          },
        ],
        //请输入原始价格
        originalPrice: [
          {
            trigger: "blur",
            required: true,
            message: "请输入原始价格",
          },
        ],
        //请输入现价
        price: [
          {
            trigger: "blur",
            required: true,
            message: "请输入现价",
          },
        ],
        //请输入VIP价格
        vipPrice: [
          {
            trigger: "blur",
            required: true,
            message: "请输入VIP价格",
          },
        ],
        //请输入商品单位
        unit: [
          {
            trigger: "blur",
            required: true,
            message: "请输入商品单位",
          },
        ],
        //请输入商品详情介绍
        productDetails: [
          {
            trigger: "blur",
            required: true,
            message: "请输入商品详情介绍",
          },
        ],
        // 商品参数名称
        attribute: [
          {
            trigger: "blur",
            required: true,
            message: "商品参数名称不能为空",
          },
        ],
        // 参数值
        value: [
          {
            trigger: "blur",
            required: true,
            message: "请输入商品参数值",
          },
        ],
        // 参数值
        status: [
          {
            trigger: "blur",
            required: true,
          },
        ],
      },
    };
  },
  created() {
    // 商品编辑数据
    this.inEdit();
    // 类目树请求
    this.productTree();
    // 运费模板
    this.freight();
  },
  methods: {
    // 批量定价点击确定
    confirmBatch() {
      let batch = this.ruleForm.skuList;
      batch.forEach((items) => {
        //批量定价--首先循环出数组为item，然后再用item点出对应的值，最后就把批量定价的值赋值过来就可以改变表格的值了
        items.price = this.formBatch.price;
        items.vipPrice = this.formBatch.vipPrice;
        items.originalPrice = this.formBatch.originalPrice;
      });

      this.diFoViBatch = false;
    },
    // 商品编辑数据
    inEdit() {
      console.log(this.$route.query.id, "商品编辑数据的i555d");
      let data = {
        _gp: "admin.product",
        _mt: "detail",
        spuId: this.$route.query.id,
      };
      http.get(data).then((res) => {
        console.log(res, "商品编辑数据123");
        let { data, errno } = res.data; //左边的data是从res.data拿出去的
        console.log(data, "mimi");
        if (200 == errno) {
          Object.assign(this.ruleForm, data);
          let arrs = [];
          arrs = this.ruleForm.imgList.map((item) => {
            return { url: item };
          });
          this.imgList = arrs;

          this.ruleForm.specificationList.forEach((item, index) => {
            let arr = [];
            item["values"] = [];
            this.ruleForm.skuList.forEach((items) => {
              arr = items.title.split(",");
              item.values.push(arr[index]);
            });
            item.values = [...new Set(item.values)];
          });
          this.createdList();
          data.skuList.forEach((item, i) => {
            Object.assign(this.ruleForm.skuList[i], item);
          });
        }
      });
    },
    createdList() {
      // reduce()四个参数分别为：初始值（或者上次回调函数的返回值），当前元素值，当前索引，调用reduce的数组
      let specificationList = this.ruleForm.specificationList;
      let titleS = specificationList.map((item) => {
        return item.title;
      });
      let valueList = specificationList
        .map((item) => {
          return item.values;
        })
        .filter((item) => {
          return item.length > 0;
        });
      //  根据属性值，生成笛卡尔直积数据
      let list = valueList.reduce(
        (total, item) => {
          let arr = [];
          total.forEach((item2) => {
            item.forEach((item3) => {
              arr.push(item2.concat([item3]));
            });
          });
          return arr;
        },
        [[]]
      );
      let { vipPrice, price, originalPrice } = this.ruleForm;
      let arry = list.map((item) => {
        let obj = {
          title: [],
          originalPrice,
          price,
          vipPrice,
          stock: 0,
          specification: [], //规格维度
          weight: "",
          barCode: "",
          img: "",
        };
        item.forEach((val, index) => {
          let key = "id_" + titleS[index]; //为了与prop进行对应，id与title拼接的都是obj中的数据
          obj[key] = val;
          obj.title.push(val);
          obj.specification.push(titleS[index] + "_" + val); //插入的是id_颜色与id_尺寸
        });
        obj.title = obj.title.join(); //将specification转成字符串
        obj.specification = obj.specification.join(); //join是为零将数组转换成字符串，最后返回给obj
        return obj;
      });

      this.ruleForm.skuList = arry;
    },
    // 成功上传图片---处理化身成功
    handleAvatarSuccess(res, file) {
      console.log("图片");
      let { errno, url } = res;
      if (200 == errno) {
        this.ruleForm.imgList.push(url);
        this.ruleForm.img = url;
      } else {
        ElMessage.warning("图片上传失败");
      }
    },
    // 商品详情的标签
    showInput(index) {
      this.ruleForm.specificationList[index].inputSkuTagVisible = true;
      //添加的表前出现
      this.$nextTick(() => {
        this.$refs["input" + index][0].focus(); //聚焦
        // this.$refs.InputRef[0]?.focus();//聚焦
      });
    },
    handleInputConfirm(inputSkuTagValue, index, ind) {
      if (inputSkuTagValue) {
        this.ruleForm.specificationList[index].values.push(inputSkuTagValue);
      }
      this.ruleForm.specificationList[index].inputSkuTagVisible = false;
      this.ruleForm.specificationList[index].inputSkuTagValue = "";
      this.createdList();
    },
    // 商品参数删除
    handleParaDelete(row) {
      console.log(row, "商品参数删除");
    },
    // 规格维度---点击确定按钮
    confirmSpace() {
      let { title } = this.formSpace; //解构赋值----这里如果不做解构赋值的话，数组就会出现后面添加的值覆盖前面的值
      if (
        this.ruleForm.specificationList.find(
          (item) => item.title == this.formSpace.title
        )
      ) {
        return ElMessage.error("该规格已存在");
      }

      this.ruleForm.specificationList.push({
        title: this.formSpace.title,
        values: [],
        inputSkuTagVisible: false,
        gmtCreate: +new Date(),
        inputSkuTagValue: "",
      });
      this.diFoViSpace = false;
      this.createdList();
    },
    // 设置商品参数---点击确定按钮
    confirmPara() {
      let { attribute, value } = this.formPara; //解构赋值----这里如果不做解构赋值的话，数组就会出现后面添加的值覆盖前面的值
      if (
        this.ruleForm.attributeList.find(
          (item) => item.attribute == this.formPara.attribute
        )
      ) {
        return ElMessage.error("该商品不能重复添加!");
      }
      this.ruleForm.attributeList.push({ attribute, value });
      this.diFoViPara = false;
    },
    // 添加规格维度
    spaceAdd() {
      // 数据初始化
      this.formSpace.title = "";
      // 显示弹框
      this.diFoViSpace = true;
    },
    // 添加商品参数
    paraAdd() {
      // 数据初始化
      this.formPara.attribute = "";
      this.formPara.value = "";
      // 显示弹框
      this.diFoViPara = true;
    },
    // 保存商品
    saveGoods() {
      let data = {
        _gp: "admin.product",
        _mt: "edit",
        spuDTO: JSON.stringify(this.ruleForm),
      };
      http
        .post(data)
        .then((res) => {
          if (200 == res.data.errno) {
            if (200 == res.data.errno) {
              ElMessageBox.confirm("是否继续编辑商品?", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
              })
                .then(() => {
                  ElMessage({
                    type: "success",
                    message: "编辑成功",
                  });
                })
                .catch(() => {
                  ElMessage({
                    type: "info",
                    message: "不再编辑商品",
                  });
                  this.$router.push({
                    path: "/Index/CategoryManagement/ProductList",
                  });
                });
            }
            ElMessage.success("成功编辑");
          }
        })
        .catch((err) => {
          console.log(123, "成功失败");
          ElMessage.error(err.data.errmsg);
        });
    },
    // 取消
    Cancel() {},
    // 运费模板
    freight() {
      let data = {
        _gp: "admin.freight",
        _mt: "list",
      };
      http.post(data).then((res) => {
        this.FreightOptions = res.data.data;
      });
    },
    // 类目树请求
    productTree() {
      let data = {
        _gp: "admin.category",
        _mt: "categoryTree",
      };
      http.post(data).then((res) => {
        this.productOptions = res.data.data;
      });
    },
  },
};
</script>
<style lang="less" scoped>
</style>
